/*
 * @Author: 肖思汗 
 * @Date: 2025-06-29 15:52:29 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-16 14:03:34
 */
import { Cell, Grid, Swiper } from '@nutui/nutui-react-taro';
import { Image, View } from '@tarojs/components';
import Taro, { pxTransform, useDidHide, useDidShow, useLoad } from '@tarojs/taro';
import chunk from 'lodash/chunk';
import { autorun, toJS } from 'mobx';
import { useEffect, useRef, useState } from 'react';
import utils from 'src/utils/utils';
import { GoodsCategoryData, MiniProgramDecorateData } from 'types/type';
import categoryStore from '../Category/categoryStore';
import GoodsCategory from './GoodsCategory/GoodsCategory';
import GoodsList from './GoodsList/GoodsList';
import hotPNG from './img/hot.png';
import styles from './index.module.less'; // 修改为模块化样式
import indexStore from './indexStore';
import SizeColorPopup from './SizeColorPopup/SizeColorPopup';

import { Tour } from '@nutui/nutui-react-taro';
import PageLayer from 'src/components/PageLayer/PageLayer';
import toDesign from 'src/subPages/Design/designComponent/toDesign';
import utilsStore from 'src/utils/utilsStore';
import userStore from '../User/userStore';
import pendantPNG from "./img/pendant.png";
import MyVideo from 'src/components/MyVideo/MyVideo';
import GoOnPreDesign from './GoOnPreDesign/GoOnPreDesign';

// 主页
const Index = () => {

    const swiperRef = useRef(null);

    const [showTour, setShowTour] = useState(false);
    const [autoPlay, setAutoPlay] = useState(false);
    const [swiperIndex, setSwiperIndex] = useState<number>(0);
    const [palying, setPalying] = useState(false);
    const [sjc, setSjc] = useState<number>(new Date().valueOf());

    useLoad(() => {
        //开启分享
        Taro.showShareMenu({
            withShareTicket: true,
        });
    })

    useEffect(() => {
        setSjc(new Date().valueOf());
    }, [])

    useDidShow(() => {
        setSjc(new Date().valueOf());
    })

    // useShareAppMessage(() => {
    //     return {
    //         title: '优T定制',
    //         path: `/subPages/AcceptInvitation/AcceptInvitation?userCode=${userInfoStore.userCode}`,
    //         imageUrl: utils.ossSuffix(myPromotionStore.promotionCode),
    //     };
    // });

    if (utils.isDev) {
        useEffect(() => {
            setTimeout(() => {
                // const url = "/subPages/DevTool/DevTool";
                // const url = "/subPages/AcceptInvitation/AcceptInvitation";
                // Taro.navigateTo({ url: "/subPages/MyOrder/MyOrder?orderState=" });
                // Taro.navigateTo({ url: "/subPages/AcceptInvitation/AcceptInvitation" });
                // Taro.navigateTo({ url: "/subPages/DevTool/DevTool" });
                // Taro.navigateTo({ url: "/pages/User/User" });
                // Taro.navigateTo({ url: "/subPages/GoodsDetail/GoodsDetail?productId=85" });
                // Taro.navigateTo({ url: "/subPages/MyDesign/MyDesign" });
                // Taro.navigateTo({ url: "/subPages/AcceptInvitation/AcceptInvitation" });
                // Taro.switchTab({ url: "/pages/User/User" });
                // Taro.navigateTo({ url: "/subPages/PromoteRelationships/PromoteRelationships" });
                // Taro.navigateTo({ url: "/subPages/IssueCoupon/IssueCoupon" }); // 发券页面
                // Taro.navigateTo({ url: "/subPages/CustomerService/CustomerService" }); // 商务合作
                // Taro.switchTab({ url: "/pages/User/User" });

                // toDesign({
                //     color: "浪漫粉",
                //     colorValue: "#f3d1c9",
                //     designName: "冰爽亲子T恤-儿童",
                //     needupload: true,
                //     productDesign: {
                //         "color": "黑色",
                //         "thumbs": ["/ugc-img/1024_1024_1756887221163.png", "/ugc-img/1024_1024_1756887221537.png"],
                //         "printArea": "double",
                //         "colorValue": "#000000",
                //         "designData": {
                //             "back": {
                //                 "version": "6.6.0", "objects": [
                //                     { "fontSize": 100, "fontFamily": "FredokaOne-Regular", "lineHeight": 1, "text": "优T设计2008508", "styles": {}, "name": "", "originWidth": 144.51151733398436, "originHeight": 45.199999999999996, "bendDegree": 0, "type": "IText", "version": "6.6.0", "originX": "center", "originY": "center", "left": 512.7819, "top": 398.8304, "width": 769.4988, "height": 113, "stroke": "#000000", "strokeWidth": 0 }]
                //             },
                //             "front": { "version": "6.6.0", "objects": [{ "id": 1756887162956, "clipPath": { "lockMovementX": false, "lockMovementY": false, "lockRotation": false, "lockScalingX": false, "lockScalingY": false, "lockSkewingX": false, "lockSkewingY": false, "inverted": false, "absolutePositioned": false, "type": "Path", "version": "6.6.0", "originX": "center", "originY": "center", "left": -276.9956, "top": -241, "width": 200, "height": 174.01, "fill": "#3c3c3c", "stroke": null, "strokeWidth": 1, "strokeDashArray": null, "strokeLineCap": "butt", "strokeDashOffset": 0, "strokeLineJoin": "miter", "strokeUniform": false, "strokeMiterLimit": 4, "scaleX": 2.77, "scaleY": 2.77, "angle": 0, "flipX": false, "flipY": false, "opacity": 1, "shadow": null, "visible": true, "backgroundColor": "", "fillRule": "nonzero", "paintFirst": "fill", "globalCompositeOperation": "source-over", "skewX": 0, "skewY": 0, "path": [["M", 200, 55.68], ["C", 199.89408272478713, 31.85458700078413, 184.70368680152666, 10.712789674566864, 162.15722974688953, 3.010919944702813], ["C", 139.6107726922524, -4.690949785161237, 114.66035487048345, 2.7387455657539945, 100, 21.520000000000003], ["C", 85.33964512951655, 2.7387455657539874, 60.38922730774759, -4.690949785161251, 37.84277025311045, 3.0109199447028097], ["C", 15.296313198473314, 10.71278967456687, 0.10591727521284611, 31.85458700078416, 0, 55.680000000000035], ["C", -0.008485099049367555, 64.56541078910325, 2.132388044594741, 73.32103300477594, 6.240000000000002, 81.2], ["L", 6.24, 81.2], ["C", 6.44, 81.58, 6.65, 81.97, 6.87, 82.36], ["C", 6.87, 82.42999999999999, 6.94, 82.5, 6.97, 82.56], ["C", 24.65, 114.63, 92.57, 168.16, 99.51, 173.56], ["L", 99.99000000000001, 174.02], ["L", 100.09, 174.02], ["C", 100.09, 174.02, 167.73000000000002, 121.54000000000002, 190.09, 87.36000000000001], ["C", 196.5653576243994, 78.06683103773031, 200.0251607692305, 67.00663289159016, 200, 55.68], ["Z"]] }, "clipSvgUrl": "/svg/399_287b265af0f6cd4de0acd8934ce503bb.svg", "type": "Image", "version": "6.6.0", "originX": "center", "originY": "center", "left": 511.6816, "top": 488.4234, "width": 642, "height": 482, "scaleX": 0.6559, "scaleY": 0.6559, "src": "https://static.uniqtee.com/ugc-img/640_480_1756887162514.jpeg?image_process=resize,w_512", "crossOrigin": "anonymous", "filters": [] }] }
                //         },
                //         "colorThumbs": [
                //             { "cn": "藏蓝", "en": "白色", "backThumbImg": "/img/1024_1024_564140_8d2cb3dad426590ec44f650ae788688e.png", "fontThumbImg": "/img/1024_1024_515056_122f5d23859002bf5d58fb178e1ed011.png" }, { "cn": "白色", "backThumbImg": "/img/1024_1024_387605_ec214af74a155c6c971bc5f8b5422c8d.png", "fontThumbImg": "/img/1024_1024_396584_3af66f2765682d18a650a40b50f46411.png" }, { "cn": "淡蓝", "en": "白色", "backThumbImg": "/img/1024_1024_637161_9695cf4c083ffd0e207d09aaf4deb193.png", "fontThumbImg": "/img/1024_1024_665253_cdf3a26190a2f53a8aeb2c0edcadd721.png" }, { "cn": "黑色", "en": "白色", "backThumbImg": "/img/1024_1024_432294_fda36614eb059747b829e751692cfcda.png", "fontThumbImg": "/img/1024_1024_445964_abe69e68f1f583047074a253fd53545f.png" },
                //             { "cn": "红色", "en": "白色", "backThumbImg": "/img/1024_1024_882979_14aeb89fcfb9576b0f55963760d74b31.png", "fontThumbImg": "/img/1024_1024_882378_d0c8259acb3f5eb33e58102dde60a5a9.png" }, { "cn": "克莱因蓝", "en": "白色", "backThumbImg": "/img/1024_1024_443996_997eda7d49ed55737c3e466b2433198c.png", "fontThumbImg": "/img/1024_1024_1145140_d5742f3273de5e9134dfc1041dec9532.png" }, { "cn": "米白", "en": "白色", "backThumbImg": "/img/1024_1024_490418_e2514f3670cef773c5eea787af9655e1.png", "fontThumbImg": "/img/1024_1024_523431_b6f5554211721afc85e9ac3d4eed7a3d.png" },
                //             { "cn": "浪漫粉", "en": "白色", "backThumbImg": "/img/1024_1024_602510_ebd5e01a0f00579e47a3b5ed4ea49f03.png", "fontThumbImg": "/img/1024_1024_787033_53753301f69de8f7fa596fcf0722d192.png" },
                //             { "cn": "薄荷绿", "en": "白色", "backThumbImg": "/img/1024_1024_702123_fd88d6c878b6df921e68db4f310a9bb4.png", "fontThumbImg": "/img/1024_1024_669685_c7e4b752ae6eb685a648d2c87dfc6f32.png" }, { "cn": "深灰", "en": "白色", "backThumbImg": "/img/1024_1024_596685_eb860f428b5e07549faa4de7a867cfd4.png", "fontThumbImg": "/img/1024_1024_674384_3dfe489d3766feeeee659d9aa5cc38d9.png" },
                //             { "cn": "开心果绿", "en": "白色", "backThumbImg": "/img/1024_1024_775219_3c04e85d3fc73c7a70131721a5fdfb74.png", "fontThumbImg": "/img/1024_1024_813441_b686e1a52b95a4b800dc594fbc753f42.png" }, { "cn": "时尚绿", "en": "白色", "backThumbImg": "/img/1024_1024_482112_298046084492bd22b0627f148eb12966.png", "fontThumbImg": "/img/1024_1024_724170_0dcbadefbcf05d3a657ef96000d7a5eb.png" }, { "cn": "胭紫", "en": "白色", "backThumbImg": "/img/1024_1024_830910_053a0a369b59271d02b356d77cc0c6df.png", "fontThumbImg": "/img/1024_1024_820692_81c8d5e1d929cd126a571a77e30c3a81.png" }, { "cn": "秋香绿", "en": "白色", "backThumbImg": "/img/1024_1024_826140_349627f3122d9e403b859c1c148d3535.png", "fontThumbImg": "/img/1024_1024_839222_732a73069c56c2bd903a439ab898fedf.png" }
                //         ],
                //         "threadColor": "#ffffff",
                //         "designThumbs": [],
                //         "previewThumb": [],
                //         "designName": "冰爽亲子T恤-成人"
                //     },
                //     productId: 118,
                //     productNegativeId: 86,
                //     size: "110"
                // });

                userStore.awaitLogined().then(() => {
                    // 杯子图片
                    const cupUrl = "https://static.uniqtee.com/img/500_660_33545_14a4bb85b9ba29b3ea10cbd5b95a4a6e.jpeg";
                    // 诸葛亮图片
                    const zglUrl = "http://static.uniqtee.com/img/1920_1568_192402_1a2576f58b022248844ed653717e07f9.jpeg";
                    // 年轻人图片
                    const yongUrl = "https://static.uniqtee.com/img/474_473_115692_176d07f7c512779de4c08cc066af8653.png";
                    // 通用扣图
                    // utilsApi.commonCutImage(cupUrl);
                    // 人体分割测试
                    // utilsApi.humanBodySeg(cupUrl);
                    // 头像分割测试
                    // utilsApi.iconSeg(cupUrl);
                    // 人像动漫化测试
                    // utilsApi.humanAnimeStyle(cupUrl);
                });
            }, 500);
        }, []);
    }

    const [goodsCategoryDatas, setGoodsCategoryDatas] = useState<Array<GoodsCategoryData>>(indexStore.goodsCategoryDatas);

    const [miniProgramDecorateData, setMiniProgramDecorateData] = useState<MiniProgramDecorateData>(toJS(indexStore.miniProgramDecorateData));

    useEffect(() => autorun(() => {
        setGoodsCategoryDatas(toJS(indexStore.goodsCategoryDatas));
        setMiniProgramDecorateData(toJS(indexStore.miniProgramDecorateData));
    }, { delay: 30 }), []);

    useDidShow(() => {
        Taro.showLoading({ title: '加载中...' });
        userStore.awaitLogined()
            .then(async () => {
                // 初始获取数据
                await indexStore.init();
            }).finally(() => {
                Taro.hideLoading();
            });

        if (swiperRef.current) {
            // console.log(swiperRef.current);
            //@ts-ignore
            swiperRef.current.to(0);
        }

        setTimeout(async () => {
            setShowTour(false);
            await new Promise(resolve => setTimeout(resolve, 100));
            if (utilsStore.showTour1) {
                utilsStore.setShowTour1(false);
                setShowTour(true);
            }
        }, 1500);

        setAutoPlay(true);
    });

    useDidHide(() => {
        setAutoPlay(false);
        setShowTour(false);
    });

    // 商品分组8个为1组
    const chunkedMenuList = chunk(goodsCategoryDatas.filter(meun => meun.id !== 48), 8);

    return (
        <PageLayer
            className={styles.index}
        >

            <Image
                className={styles.pendant}
                src={pendantPNG}
                mode="heightFix"
            />

            <Swiper
                defaultValue={0}
                loop
                autoPlay={autoPlay && !palying}
                indicator
                height={pxTransform(200)}
                ref={swiperRef}
                className={styles.swiper}
                onChange={(e) => {
                    // console.log("swiper:", e);
                }}
                onAnimationFinish={(e) => {
                    setSwiperIndex(e.detail.current);
                }}
            >
                {miniProgramDecorateData.sysSlideshows.map((item, index) => (
                    <Swiper.Item key={index}>
                        {
                            /(jpg|png|peg|webp)$/i.test(item.slideshowUrl) &&
                            <Image
                                style={{ width: '100%', height: '100%' }}
                                onClick={() => {
                                    if (item.skipAddr) {
                                        Taro.navigateTo({
                                            url: item.skipAddr
                                        });
                                    }
                                }}
                                mode="aspectFill"
                                src={utils.ossSuffix(item.slideshowUrl, 1000)}
                            />
                        }
                        {
                            /(mp4)$/i.test(item.slideshowUrl) &&
                            <MyVideo
                                className={styles.video}
                                style={{ width: '100%', height: '100%' }}
                                src={utils.ossSuffix(item.slideshowUrl)}
                                resetIndex={sjc + swiperIndex}
                                startPlay={() => {
                                    setPalying(true);
                                }}
                                stopPlay={() => {
                                    setPalying(false);
                                }}
                            />
                        }

                    </Swiper.Item>
                ))}
            </Swiper>

            {
                miniProgramDecorateData.ifGoodsCategoryShow &&
                <View className={styles.menuSwiper} id="menuSwiper" >
                    <Swiper
                        height={goodsCategoryDatas.length < 5 ? pxTransform(80) : pxTransform(170)}
                        className={styles.menuSwiperContent}
                    >
                        {chunkedMenuList.map((page, pageIndex) => (
                            <Swiper.Item key={pageIndex}>
                                <Grid columns={4} square>
                                    {page.map((menu, index) => (
                                        <Grid.Item
                                            key={index}
                                            text={menu.typeName}
                                        >
                                            <Image
                                                src={utils.ossSuffix(menu.typeIcon, 80)}
                                                className={styles.menuImage}
                                                mode="aspectFit"
                                                onClick={() => {
                                                    Taro.switchTab({
                                                        url: '/pages/Category/Category',
                                                        success: () => {
                                                            categoryStore.setActiveFirstProductType(menu.id);
                                                        }
                                                    });
                                                }}
                                            />
                                        </Grid.Item>
                                    ))}
                                </Grid>
                            </Swiper.Item>
                        ))}
                    </Swiper>
                </View>
            }

            {/* 继续上次的设计 */}
            <GoOnPreDesign />

            {
                miniProgramDecorateData.ifGoodsCategoryShow &&
                <>
                    {/* 热门商品 */}
                    <Cell.Group>
                        <Cell
                            title={
                                <Image
                                    src={hotPNG}
                                    style={{
                                        width: pxTransform(90),
                                        height: pxTransform(30),
                                    }}
                                />
                            }
                            align="center"
                            onTouchStart={() => { }}
                        />
                    </Cell.Group>
                    {/* 商品分类 */}
                    <GoodsCategory />

                    {/* 商品列表 */}
                    <GoodsList />
                </>
            }

            {/* 颜色尺码弹出层 */}
            <SizeColorPopup />

            <Tour
                className="nut-custom-tour"
                visible={showTour}
                onClose={() => {
                    utilsStore.setShowTour1(false);
                    setShowTour(false);
                }}
                list={[
                    {
                        content: '1.选择一个分类',
                        target: 'menuSwiper',
                    }
                ]}
                location="top-start"
                offset={[0, 0]}
                maskWidth={utilsStore.windowWidth}
                maskHeight={goodsCategoryDatas.length < 5 ? utils.rpx2px(170) : utils.rpx2px(340)}
            />

        </PageLayer>
    );
};

export default Index;

